package ru.jkff.jalgebra.monoid;

import static ru.jkff.jalgebra.utils.CollectionFactory.newUnorderedMap;

import java.util.Map;
import java.util.Set;

/**
 * User: jkff
 * Date: Aug 22, 2009
 * Time: 12:40:56 PM
 */
public final class AggregateMap<K,V,R> {
    private Aggregate<V,R> aggregate;
    private Map<K,R> key2res = newUnorderedMap();

    public AggregateMap(Aggregate<V,R> aggregate) {
        this.aggregate = aggregate;
    }

    public R get(K key) {
        R r = key2res.get(key);
        if(r == null) {
            key2res.put(key, r = aggregate.freshUnit());
        }
        return r;
    }

    public void push(K key, V value) {
        aggregate.pushInto(value, get(key));
    }

    public void mergeIntoSelf(AggregateMap<K,?,R> other) {
        for(K k : other.explicitKeySet()) {
            aggregate.mergeInto(get(k), other.get(k));
        }
    }

    public Set<K> explicitKeySet() {
        return key2res.keySet();
    }
}
